/*
 * Copyright 2020 lcnap
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package pers.lcnap.simplerpc.rpc;

import pers.lcnap.RpcClient;
import pers.lcnap.RpcRequest;
import pers.lcnap.RpcResponse;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 代理类实现，用于发起 Rpc 请求。
 *
 * @see RpcClient#init(Class[])
 */
public class RpcInvocationHandler implements InvocationHandler {

    private RpcClient client;

    public RpcInvocationHandler(RpcClient client) {
        this.client = client;

    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result;
        if (method.getDeclaringClass().equals(Object.class)) {
            //转发到InvocationHandler
            return method.invoke(this, args);
        }

        RpcRequest request = new RpcRequest(
                method.getDeclaringClass().getName(),
                method.getName(),
                args,
                method.getParameterTypes());

        AtomicReference<Object> response = new AtomicReference<>();
        client.send(request, future -> {
            if (future.isSuccess()) {
                response.set(future.getNow());
            } else {
                response.set(future.cause());
            }
        });
        long start = System.currentTimeMillis();
        while (response.get() == null) {
            long now = System.currentTimeMillis();
            if (now - start > client.getTimeout())
                throw new RpcRuntimeException("time out " + client.getTimeout());
        }

        result = response.get();
        if (result instanceof RpcResponse){
            return ((RpcResponse) result).getResult();
        }
        throw (Throwable) result;
    }
}
